package com.ziytek.web.citizen;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 服务重启
 *
 * @author fenghx
 */
@Slf4j
@Service
public class ReBootService {

    private static final String OS_WIN = "win";
    private static final String OS_NAME = "os.name";

    @Async("virtualThreadExecutor")
    public void rebootRun() {
        // 仅当在Windows下运行时启动监控
        if (System.getProperty(OS_NAME).toLowerCase().contains(OS_WIN)) {
            log.info("当前操作系统为Windows");

            // 使用端口占用情况,检查服务监听程序是否运行
            if (PortCheckerUtil.isPortInUse(ServerConstant.PORT_TCP) && PortCheckerUtil.isPortInUse(ServerConstant.PORT_SERVER)) {
                log.info("检查后台服务程序已运行,请勿重复启动!");
                // 弹出窗口 提示
                //JOptionPane.showMessageDialog(null, "程序已运行,请勿重复启动!");
                return;
            }

            // 本地运行路线
            //String path = System.getProperty("user.dir") + "\\runtime\\bin";
            var path = System.getProperty("user.dir");
            log.info("本地路径:{}", path);
            // bike-cabinet-sba-web-0.0.1-SNAPSHOT.jar
            //start /B javaw -jar bike-cabinet-sba-web-0.0.1-SNAPSHOT.jar
            // C:\Users\fengh\AppData\Local\JtCabinet\runtime\bin
            //String cmd =  "cmd.exe /c start \"\" /B C:\\Users\\fengh\\AppData\\Local\\JtCabinet\\runtime\\bin\\java -jar " + path + "\\bike-cabinet-sba-web-0.0.1-SNAPSHOT.jar";
            var cmd = " cmd.exe /c start \"\" /B C:\\Users\\fengh\\AppData\\Local\\JtCabinet\\runtime\\bin\\java -jar C:\\Users\\fengh\\AppData\\Local\\JtCabinet\\app\\bike-cabinet-web-0.0.1-SNAPSHOT.jar" +
                    " --server.port=14885 ";

            cmd = " cmd.exe /c start \"\" /B " + path + "\\runtime\\bin\\javaw -jar "
                    + path +
                    "\\app\\bike-cabinet-web-0.0.1-SNAPSHOT.jar --server.port=14885 ";

            cmd = " cmd.exe /c start \"\" /B C:\\Users\\fengh\\AppData\\Local\\JtCabinet\\JtCabinet.exe";

            log.info("后台服务程序重新启动,执行的cmd命令:{}", cmd);

            try {
                var process = Runtime.getRuntime().exec(cmd);

                // 读取进程的输出和错误流
                //var reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                var errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                String line;
//                while ((line = reader.readLine()) != null) {
//                    // log.info("运行正常: " + line);
//                }

                while ((line = errorReader.readLine()) != null) {
                    log.error("运行出错: {}", line);
                }

                // 等待进程结束
                log.info("启动检查服务监听程序完成Exited with code:{} ", process.waitFor());
            } catch (IOException | InterruptedException e) {
                log.error("启动检查服务监听程序失败", e);
            }
        }
    }

    @Async("virtualThreadExecutor")
    public void rebootRunExe() {
        // 仅当在Windows下运行时启动监控
        if (System.getProperty(OS_NAME).toLowerCase().contains(OS_WIN)) {
            log.info("rebootRunExe当前操作系统为Windows");

            // 使用端口占用情况,检查服务监听程序是否运行
            if (PortCheckerUtil.isPortInUse(ServerConstant.PORT_TCP) && PortCheckerUtil.isPortInUse(ServerConstant.PORT_SERVER)) {
                log.info("rebootRunExe检查后台服务程序已运行,请勿重复启动!");
                // 弹出窗口 提示
                //JOptionPane.showMessageDialog(null, "程序已运行,请勿重复启动!");
                return;
            }

            // 本地运行路线
            //String path = System.getProperty("user.dir") + "\\runtime\\bin";
            var path = System.getProperty("user.dir");
            log.info("rebootRunExe本地路径:{}", path);

            try {
                String cmd = "C:\\Users\\fengh\\AppData\\Local\\JtCabinet\\JtCabinet.exe";
                cmd = path + "\\JtCabinet.exe";
                File exeFile = new File(cmd);
                if (!exeFile.exists()) {
                    log.error("指定的可执行文件不存在: {}", exeFile.getAbsolutePath());
                    return;
                }

                log.info("rebootRunExe执行的cmd命令:{}", cmd);
                ProcessBuilder builder = new ProcessBuilder(cmd);
                // 将错误输出和标准输出合并
                builder.redirectErrorStream(true);
                Process process = builder.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }

                // 等待进程结束
                log.info("exe启动检查服务监听程序完成Exited with code: {}", process.waitFor());
            } catch (IOException e) {
                log.error("启动检查服务监听程序失败", e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
